import { websocket } from '@/utils/websocket'
import store from './../index'
import { getToken } from '@/utils/auth' // get token from cookie
 
const state = {
  message: {},
  ws: null
}
 
const mutations = {
  SET_MESSAGE: (state, message) => {
    state.message = message
  },
  SET_WS: (state, ws) => {
    state.ws = ws
  }
}
 
const actions = {
  websocketMsg({ commit }) {
    return new Promise((resolve, reject) => {
      websocket().then((ws) => {
        commit('SET_WS', ws)
        ws.onopen = function() {
          // Web Socket 已连接上，使用 send() 方法发送数据
          ws.send('发送数据')
        }
 
        ws.onmessage = function(evt) {
          var received_msg = evt.data
          commit('SET_MESSAGE', received_msg)
        }
        ws.onerror = function(error) {
          reject(error)
        }
        ws.onclose = function() {
          // 关闭 websocket
          // alert("连接已关闭...");
          if (getToken()) {
            store.dispatch('message/websocketMsg')
          }
        }
        resolve()
      })
    })
  }
}
 
export default {
  namespaced: true,
  state,
  mutations,
  actions
}